import { useCallback, useEffect, useMemo, useState } from 'react';
import { class_esy, isArray, isEmpty, StarOutlined } from 'esy-ui';
import { observer } from 'mobx-react-lite';
import { useFormatText, useNavigation } from '@/hooks';
import { Empty, Img } from '@/components';
import type { UserInfoStateType } from '@/mobx';
import { postHisPlayGame, postHotRecommendGame } from '@/services';
import { useGame } from '@/hooks/useGame';
import { useOtherStore } from '@/mobx/other';

const url = 'https://g1.torry.vip/game_picture/mobile/58/58053.png?v=1731640826';
const quickGame = [
  { id: 1, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 2, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 3, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 4, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 5, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 6, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 7, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 8, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 9, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 10, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 11, url, name: 'RG', desc: '随便一点', cols: 2 },
  { id: 12, url, name: 'RG', desc: '随便一点随便一点', cols: 2 },
];

const types = [
  {
    tKey: 'text_27',
    key: '1',
  },
  {
    tKey: 'text_28',
    key: '2',
  },
  {
    tKey: 'text_7',
    key: '3',
  },
];

function QuickContent(props: UserInfoStateType) {
  const { Token } = props;
  const navigation = useNavigation();
  const { collets, isCollet, colletCount } = useOtherStore();
  const { clickGame, clickCollct } = useGame(Token);
  const { text } = useFormatText();
  const [open, setOpen] = useState(false);
  // 1 最近玩过 2 我的收藏 3 热门推荐
  const [type, setType] = useState<string>('3');
  const [data, setData] = useState<{ key: string; list: any[] }>();

  console.info(colletCount);

  const getHot = useCallback(() => {
    postHotRecommendGame({})
      .then((res: any) => {
        setData((preo) => ({ ...preo, 3: res.Data }));
      })
      .catch(() => {
        setData((preo) => ({ ...preo, 3: quickGame }));
      });
  }, []);

  const getGame = useCallback(() => {
    if (!Token) return;
    postHisPlayGame({})
      .then((res: any) => {
        setData((preo) => ({ ...preo, 1: res.Data }));
      })
      .catch(() => {});
  }, [Token]);

  useEffect(() => {
    getGame();
  }, [getGame]);

  useEffect(() => {
    getHot();
  }, [getHot]);

  const changeType = (k: string) => {
    if (Token) {
      setType(k);
    }
  };

  const goGame = (info) => {
    if (Token) {
      clickGame(info?.Gid);
    } else {
      navigation('/login');
    }
  };

  const getH = () => {
    if (open) {
      return Token ? 'h-64' : 'h-52';
    }
    return 'h-0';
  };

  // 获取列表数据
  const list = useMemo(() => {
    let ds = [];
    if (['1', '3'].includes(type)) {
      if (!isEmpty(data)) ds = data[type];
    } else if (colletCount > 0) {
      collets.forEach((value) => {
        ds.push(value);
      });
    }
    if (isArray(ds) && ds.length > 2 && ds.length < 12) {
      const len = 12 - ds.length;
      for (let i = 0; i <= len; i++) {
        ds.push({ Id: `insert-${i}` });
      }
    }
    return ds;
  }, [type, collets, colletCount, data]);

  return (
    <div className='absolute left-0 w-full bottom-full'>
      <div className='border-b-2 border-primary w-full'>
        <span
          className='absolute top-0 bg-primary text-bdr text-sm px-1 rounded-t left-1/2 -translate-x-1/2 -translate-y-full'
          onClick={() => {
            setOpen(!open);
          }}
        >
          {text('text_8')}
        </span>
      </div>
      <div className={class_esy(['bg-head overflow-y-hidden flex flex-col transform-height duration-300 ease-in', getH()])}>
        <div className='bg-black flex items-center'>
          {(Token ? types : types.slice(-1)).map((it) => (
            <div key={it.key} className={class_esy(['text-xs py-2 px-3 flex items-center gap-1', type === it.key ? 'text-primary bg-head' : 'text-desc'])} onClick={() => changeType(it.key)}>
              {it.key === '2' ? <StarOutlined className='text-sm' /> : ''}
              {text(it.tKey)}
            </div>
          ))}
        </div>
        <div className='gap-2 mt-2 px-2 flex flex-col flex-wrap overflow-x-auto flex-1'>
          {isArray(list) && !isEmpty(list) ? (
            list.map((it) => {
              if (typeof it.Id === 'string') {
                return <div className='relative w-14 h-24 opacity-0' />;
              }
              return (
                <div key={it.Id || it.id} className='relative w-14'>
                  <div
                    onClick={() => {
                      goGame(it);
                    }}
                  >
                    <Img boxClassName='w-14 h-14' src={it.TitleImage || it.url} />
                    <div className='text-xs text-name truncate text-center mt-1'>{it.Describe}</div>
                  </div>
                  {Token ? (
                    <div
                      className={class_esy([
                        'flex items-center justify-center mx-auto mt-1 py-0.5 w-12 border border-solid rounded',
                        isCollet(it?.Gid) ? 'bg-primary text-black' : 'text-white border-white',
                      ])}
                      onClick={() => {
                        clickCollct(it?.Gid);
                      }}
                    >
                      <StarOutlined className='text-xs' />
                    </div>
                  ) : null}
                </div>
              );
            })
          ) : (
            <Empty />
          )}
        </div>
      </div>
    </div>
  );
}

export default observer(QuickContent);
